import axios from 'axios'
import {
  Message,
} from 'element-ui'
// 设置axios为form-data
import qs from 'qs'

axios.defaults.baseURL = localStorage.getItem('baseURL');

const http = axios.create({})

// 添加请求拦截器
http.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  config.headers['token'] = localStorage.getItem('token');
  if (config.data instanceof FormData) {
    return config
  }
  if(config.method === 'post'){
    if(config.data&&config.data.array){
      return config
    }
    config.data = qs.stringify(config.data,{ arrayFormat: 'brackets' })
  }
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})
http.interceptors.response.use(function(res){
  let data = res.data;
  if (data.Code === 200) {
    !data.Data && (data.Data = '{}')
    return Promise.resolve(data)
  } else if (data.Code === 401) {
    Message({
      showClose: true,
      message: '登录验证失败，请重新登录！',
      type: 'error'
    })
    that.$router.push('/Login')
  } else {
    let str = '请求失败，请重试！'
    if (data.Msg) {
      str = data.Msg
    }
    Message({
      showClose: true,
      message: str,
      type: 'error'
    })
  }
},function(error){
  return Promise.reject(error)
})
export default http
